<template>
  <main class="max-w-6xl mx-auto px-6">
    <!-- 顶部信息区 -->
    <div class="flex flex-col gap-3 mb-6">
      <div class="flex items-center justify-between">
        <div>
          <div class="flex items-center gap-2">
            <div class="w-2 bg-yellow-200 h-8"></div>
            <div class="text-2xl font-bold">图片素材库</div>
          </div>
          <div class="text-gray-400 text-sm mt-1">
            共 {{ totalCount }} 张图片
          </div>
        </div>
        <div class="flex gap-2">
          <Button
            variant="outline"
            size="icon"
            :class="{ 'bg-primary/10 text-primary': viewMode === 'grid' }"
            @click="viewMode = 'grid'"
          >
            <svg
              class="w-5 h-5"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <rect x="3" y="3" width="7" height="7" rx="2" />
              <rect x="14" y="3" width="7" height="7" rx="2" />
              <rect x="14" y="14" width="7" height="7" rx="2" />
              <rect x="3" y="14" width="7" height="7" rx="2" />
            </svg>
          </Button>
          <Button
            variant="outline"
            size="icon"
            :class="{ 'bg-primary/10 text-primary': viewMode === 'list' }"
            @click="viewMode = 'list'"
          >
            <svg
              class="w-5 h-5"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <rect x="3" y="5" width="18" height="4" rx="2" />
              <rect x="3" y="15" width="18" height="4" rx="2" />
            </svg>
          </Button>
          <Button
            variant="outline"
            size="icon"
            :class="{ 'bg-primary/10 text-primary': showFilters }"
            @click="toggleFilters"
          >
            <svg
              class="w-5 h-5"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                stroke-linecap="round"
                stroke-linejoin="round"
                stroke-width="2"
                d="M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.207A1 1 0 013 6.5V4z"
              />
            </svg>
          </Button>
        </div>
      </div>
      <!-- 选中图片信息展示 -->
      <Transition name="detail-fade" mode="out-in">
        <div
          v-if="selectedImage"
          key="selected"
          class="bg-gray-50 border border-gray-200 rounded-lg p-4 mb-4"
        >
          <div class="flex items-center gap-4">
            <!-- 选中图片缩略图 -->
            <div class="flex-shrink-0">
              <img
                :src="selectedImage.url"
                :alt="selectedImage.name"
                class="w-16 h-16 object-cover rounded-lg border"
              />
            </div>
            <!-- 选中图片信息 -->
            <div class="flex-1 min-w-0">
              <div class="flex items-center justify-between mb-1">
                <div class="font-medium text-lg truncate">
                  {{ selectedImage.originalName.split(".")[0] }}
                  <Badge variant="secondary">
                    {{ selectedImage.originalName.split(".")[1] }}
                  </Badge>
                </div>
                <Button
                  variant="outline"
                  size="sm"
                  @click="clearSelection"
                  class="flex-shrink-0"
                >
                  <svg
                    class="w-4 h-4 mr-1"
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                  >
                    <path
                      stroke-linecap="round"
                      stroke-linejoin="round"
                      stroke-width="2"
                      d="M6 18L18 6M6 6l12 12"
                    />
                  </svg>
                  取消选择
                </Button>
              </div>
              <div class="flex flex-wrap gap-2 mb-2">
                <span
                  v-for="(tag, idx) in selectedImage.tags"
                  :key="tag"
                  :class="`${getTagColor(tag, idx).bg} ${
                    getTagColor(tag, idx).text
                  } rounded-full px-2 py-1 text-xs`"
                >
                  {{ tag }}
                </span>
              </div>
              <div class="text-sm text-gray-500">
                使用 {{ selectedImage.usedCount }} 次 ·
                {{ formatDate(selectedImage.uploadTime) }}
              </div>
            </div>
          </div>

          <!-- 功能指引区域 -->
          <div class="mt-4 pt-4 border-t border-gray-200">
            <div class="text-sm font-medium text-gray-700 mb-3">
              基于此图片，您可以：
            </div>
            <div class="flex gap-3">
              <Button
                size="sm"
                variant="outline"
                class="flex-1"
                @click="goToTextGeneration"
              >
                <svg
                  class="w-4 h-4 mr-2"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    stroke-width="2"
                    d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
                  />
                </svg>
                生成相关文案
              </Button>
              <Button
                size="sm"
                variant="outline"
                class="flex-1"
                @click="goToImageExpansion"
              >
                <svg
                  class="w-4 h-4 mr-2"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    stroke-width="2"
                    d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"
                  />
                </svg>
                图片扩展
              </Button>
            </div>
          </div>
        </div>
      </Transition>

      <!-- 搜索栏 -->
      <div class="flex gap-2 items-center">
        <Input
          v-model="search"
          placeholder="搜索图片名称或标签..."
          class="flex-1"
          @input="handleSearchInput"
          @compositionstart="handleCompositionStart"
          @compositionend="handleCompositionEnd"
          @keydown.enter="handleSearchEnter"
        />
        <!-- 搜索状态指示器 -->
        <div
          v-if="isSearching"
          class="flex items-center gap-2 text-sm text-gray-500"
        >
          <svg
            class="w-4 h-4 animate-spin"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              stroke-linecap="round"
              stroke-linejoin="round"
              stroke-width="2"
              d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"
            />
          </svg>
          搜索中...
        </div>
      </div>

      <!-- 增强的筛选和排序工具栏 -->
      <Transition
        enter-active-class="transition-all duration-300 ease-out"
        enter-from-class="opacity-0 transform -translate-y-4"
        enter-to-class="opacity-100 transform translate-y-0"
        leave-active-class="transition-all duration-200 ease-in"
        leave-from-class="opacity-100 transform translate-y-0"
        leave-to-class="opacity-0 transform -translate-y-4"
      >
        <div
          v-if="showFilters"
          class="flex flex-col gap-3 bg-gray-50 rounded-lg p-4"
        >
          <div class="flex flex-wrap items-center gap-4">
            <!-- 排序方式 -->
            <div class="flex items-center gap-2">
              <span class="text-sm font-medium text-gray-700">排序:</span>
              <Select v-model="sortMode" @update:model-value="handleSortChange">
                <SelectTrigger class="w-32">
                  <span v-if="sortMode === 'time'">按时间</span>
                  <span v-else>按使用</span>
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="time">按时间排序</SelectItem>
                  <SelectItem value="count">按使用次数</SelectItem>
                </SelectContent>
              </Select>
              <!-- 排序方向 -->
              <Select
                v-model="sortDirection"
                @update:model-value="handleSortDirectionChange"
              >
                <SelectTrigger class="w-24">
                  <span>{{ sortDirection === "desc" ? "倒序" : "正序" }}</span>
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="desc">倒序</SelectItem>
                  <SelectItem value="asc">正序</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <!-- 时间范围筛选 -->
            <div class="flex items-center gap-2">
              <span class="text-sm font-medium text-gray-700">时间范围:</span>
              <Select
                v-model="timeRange"
                @update:model-value="handleTimeRangeChange"
              >
                <SelectTrigger class="w-32">
                  <span>{{ getTimeRangeLabel(timeRange) }}</span>
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部时间</SelectItem>
                  <SelectItem value="today">24小时</SelectItem>
                  <SelectItem value="week">本周</SelectItem>
                  <SelectItem value="month">本月</SelectItem>
                  <SelectItem value="quarter">本季度</SelectItem>
                  <SelectItem value="year">今年</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <!-- 使用次数筛选 -->
            <div class="flex items-center gap-2">
              <span class="text-sm font-medium text-gray-700">使用次数:</span>
              <Select
                v-model="usageFilter"
                @update:model-value="handleUsageFilterChange"
              >
                <SelectTrigger class="w-32">
                  <span>{{ getUsageFilterLabel(usageFilter) }}</span>
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部</SelectItem>
                  <SelectItem value="unused">未使用</SelectItem>
                  <SelectItem value="low">使用较少 (1-5次)</SelectItem>
                  <SelectItem value="medium">使用中等 (6-20次)</SelectItem>
                  <SelectItem value="high">使用频繁 (20+次)</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <!-- 清除筛选 -->
            <Button
              variant="outline"
              size="sm"
              @click="clearAllFilters"
              class="ml-auto"
            >
              <svg
                class="size-4"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  stroke-width="2"
                  d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"
                />
              </svg>
            </Button>
          </div>
          <!-- 多标签筛选 -->
          <div class="flex items-start gap-2">
            <span class="text-sm font-medium text-gray-700 w-10">标签:</span>
            <div class="flex flex-wrap gap-2">
              <!-- 加载状态 -->
              <div
                v-if="isLoadingTags"
                class="flex items-center gap-2 text-sm text-gray-500"
              >
                <svg
                  class="w-4 h-4 animate-spin"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    stroke-width="2"
                    d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"
                  />
                </svg>
                加载标签中...
              </div>

              <!-- 错误状态 -->
              <div
                v-else-if="tagsError"
                class="flex items-center gap-2 text-sm text-red-500"
              >
                <svg
                  class="w-4 h-4"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    stroke-width="2"
                    d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
                  />
                </svg>
                {{ tagsError }}
                <Button
                  variant="ghost"
                  size="sm"
                  @click="fetchAllTags"
                  class="text-xs"
                >
                  重试
                </Button>
              </div>

              <!-- 标签列表 -->
              <template v-else>
                <button
                  v-for="tag in allTags"
                  :key="tag"
                  class="px-3 py-1 text-xs rounded-full border transition-colors"
                  :class="
                    selectedTags.includes(tag)
                      ? 'bg-primary text-white border-primary'
                      : 'bg-white text-gray-600 border-gray-300 hover:border-primary hover:text-primary'
                  "
                  @click="toggleTag(tag)"
                >
                  {{ tag }}
                </button>

                <!-- 无标签提示 -->
                <div v-if="allTags.length === 0" class="text-sm text-gray-400">
                  暂无标签
                </div>
              </template>
            </div>
          </div>
        </div>
      </Transition>
    </div>

    <!-- 图片网格区域 -->
    <div class="h-[calc(100vh-280px)]">
      <ScrollArea class="h-full w-full rounded-md border">
        <div class="p-4">
          <!-- 图片网格/列表切换动画 -->
          <Transition name="material-fade" mode="out-in">
            <div
              v-if="viewMode === 'grid'"
              key="grid"
              class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-6"
            >
              <div
                v-for="img in paginatedImages"
                :key="img.id"
                class="relative group"
              >
                <div
                  class="rounded-2xl border bg-white shadow-sm hover:shadow-lg transition-all duration-150 overflow-hidden cursor-pointer h-full flex flex-col"
                  :class="
                    selectedImageId === img.id
                      ? 'border-2 border-primary'
                      : 'border border-gray-200'
                  "
                  @click="selectImage(img.id)"
                >
                  <ImagePreview
                    :src="img.url"
                    :alt="img.name"
                    container-class="h-48"
                    @preview="handleImagePreview"
                  />
                  <div class="flex-1 flex flex-col p-4 pb-3">
                    <div class="flex items-center justify-between">
                      <div class="font-medium text-base truncate mb-2">
                        {{ (img.originalName || "").split(".")[0] }}
                      </div>
                      <Badge variant="secondary" class="mb-1">
                        {{ (img.originalName || "").split(".")[1] }}
                      </Badge>
                    </div>
                    <div class="flex flex-wrap gap-1 mb-2">
                      <template v-for="(tag, idx) in displayTags(img.tags)">
                        <span
                          v-if="tag !== '__more__'"
                          :key="tag"
                          :class="`${getTagColor(tag, idx).bg} ${
                            getTagColor(tag, idx).text
                          } rounded-full px-2 py-1 text-xs`"
                          >{{ tag }}</span
                        >
                        <span
                          v-else
                          :key="'more'"
                          :class="`${getTagColor(tag, idx).bg} ${
                            getTagColor(tag, idx).text
                          } rounded-full px-2 py-1 text-xs`"
                          >+{{ img.tags.length - 2 }}</span
                        >
                      </template>
                    </div>
                    <div class="text-xs text-gray-400 mt-auto">
                      使用 {{ img.usedCount }} 次 ·
                      {{ formatDate(img.uploadTime) }}
                    </div>
                  </div>
                  <!-- 选中指示器 -->
                  <div
                    v-if="selectedImageId === img.id"
                    class="absolute top-2 right-2 w-6 h-6 bg-primary rounded-full flex items-center justify-center text-white shadow-lg"
                  >
                    <svg
                      class="w-4 h-4"
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                    >
                      <path
                        stroke-linecap="round"
                        stroke-linejoin="round"
                        stroke-width="3"
                        d="M5 13l4 4L19 7"
                      />
                    </svg>
                  </div>

                  <!-- 删除按钮 -->
                  <div
                    class="absolute top-2 left-2 opacity-0 group-hover:opacity-100 transition-opacity duration-200"
                  >
                    <Button
                      size="icon"
                      variant="destructive"
                      class="w-6 h-6 bg-red-500 hover:bg-red-600 text-white"
                      @click.stop="openDeleteDialog(img)"
                    >
                      <svg
                        class="w-3 h-3"
                        fill="none"
                        stroke="currentColor"
                        viewBox="0 0 24 24"
                      >
                        <path
                          stroke-linecap="round"
                          stroke-linejoin="round"
                          stroke-width="2"
                          d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
                        />
                      </svg>
                    </Button>
                  </div>

                  <!-- 收藏按钮 -->
                  <div
                    class="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity duration-200"
                  >
                    <Button
                      size="icon"
                      variant="outline"
                      class="w-6 h-6 bg-gray-50 hover:bg-gray-100"
                      :class="
                        img.isFavorite ? 'text-pink-500' : 'text-gray-400'
                      "
                      @click.stop="toggleFavorite(img)"
                    >
                      <svg
                        class="w-3 h-3"
                        :fill="img.isFavorite ? 'currentColor' : 'none'"
                        stroke="currentColor"
                        viewBox="0 0 24 24"
                      >
                        <path
                          stroke-linecap="round"
                          stroke-linejoin="round"
                          stroke-width="2"
                          d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41 0.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"
                        />
                      </svg>
                    </Button>
                  </div>
                </div>
              </div>
            </div>
            <div v-else key="list" class="space-y-3">
              <div
                v-for="img in paginatedImages"
                :key="img.id"
                class="flex items-center gap-4 p-4 bg-white rounded-lg border hover:shadow-lg transition-all duration-150 cursor-pointer"
                :class="
                  selectedImageId === img.id
                    ? 'border-2 border-primary bg-primary/5'
                    : 'border-gray-200'
                "
                @click="selectImage(img.id)"
              >
                <!-- 缩略图 -->
                <div class="relative flex-shrink-0">
                  <ImagePreview
                    :src="img.url"
                    :alt="img.name"
                    container-class="w-20 h-20 rounded-lg"
                    @preview="handleImagePreview"
                  />
                  <div
                    v-if="selectedImageId === img.id"
                    class="absolute top-1 right-1 w-5 h-5 bg-primary rounded-full flex items-center justify-center text-white shadow-lg z-10"
                  >
                    <svg
                      class="w-3 h-3"
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                    >
                      <path
                        stroke-linecap="round"
                        stroke-linejoin="round"
                        stroke-width="2"
                        d="M5 13l4 4L19 7"
                      />
                    </svg>
                  </div>
                </div>

                <!-- 图片信息 -->
                <div class="flex-1 min-w-0">
                  <div class="flex items-center justify-between mb-2">
                    <div class="font-medium text-lg truncate">
                      {{ (img.originalName || "").split(".")[0] }}
                      <Badge variant="secondary">
                        {{ (img.originalName || "").split(".")[1] }}
                      </Badge>
                    </div>
                  </div>

                  <!-- 标签 -->
                  <div class="flex flex-wrap gap-2 mb-2">
                    <span
                      v-for="(tag, idx) in img.tags"
                      :key="tag"
                      :class="`${getTagColor(tag, idx).bg} ${
                        getTagColor(tag, idx).text
                      } rounded-full px-2 py-1 text-xs`"
                    >
                      {{ tag }}
                    </span>
                  </div>

                  <!-- 使用信息 -->
                  <div class="text-sm text-gray-400">
                    <span>上传于 {{ formatDate(img.uploadTime) }}</span>
                    <span class="mx-2">·</span>
                    <span>使用 {{ img.usedCount }} 次</span>
                  </div>
                </div>

                <!-- 操作按钮 -->
                <div class="flex items-center gap-2 flex-shrink-0">
                  <Button
                    size="sm"
                    variant="outline"
                    @click.stop="openPreviewModal(img)"
                  >
                    预览
                  </Button>
                  <Button
                    size="sm"
                    variant="outline"
                    @click.stop="downloadImage(img)"
                  >
                    下载
                  </Button>
                  <Button
                    size="sm"
                    variant="destructive"
                    @click.stop="openDeleteDialog(img)"
                  >
                    <svg
                      class="w-4 h-4 mr-1"
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                    >
                      <path
                        stroke-linecap="round"
                        stroke-linejoin="round"
                        stroke-width="2"
                        d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
                      />
                    </svg>
                    删除
                  </Button>
                </div>
              </div>
            </div>
          </Transition>
        </div>
      </ScrollArea>
    </div>

    <!-- 分页控件 -->
    <div v-if="totalCount > pageSize" class="flex justify-center my-6">
      <div class="flex gap-2 items-center">
        <Button
          variant="outline"
          size="sm"
          :disabled="currentPage === 1"
          @click="currentPage = 1"
        >
          首页
        </Button>
        <Button
          variant="outline"
          size="sm"
          :disabled="currentPage === 1"
          @click="currentPage--"
        >
          上一页
        </Button>
        <span class="px-4 text-sm text-gray-600">
          {{ currentPage }} / {{ totalPages }}
        </span>
        <Button
          variant="outline"
          size="sm"
          :disabled="currentPage === totalPages"
          @click="currentPage++"
        >
          下一页
        </Button>
        <Button
          variant="outline"
          size="sm"
          :disabled="currentPage === totalPages"
          @click="currentPage = totalPages"
        >
          末页
        </Button>
      </div>
    </div>

    <!-- 调试信息 -->
    <div v-if="false" class="text-xs text-gray-400 text-center mb-4">
      调试信息: totalCount={{ totalCount }}, totalPages={{ totalPages }},
      currentPage={{ currentPage }}, pageSize={{ pageSize }}
    </div>

    <!-- 删除确认对话框 -->
    <AlertDialog v-model:open="deleteDialogOpen">
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>确认删除</AlertDialogTitle>
          <AlertDialogDescription>
            您确定要删除图片 "{{ imageToDelete?.name }}" 吗？此操作无法撤销。
          </AlertDialogDescription>
        </AlertDialogHeader>
        <AlertDialogFooter>
          <AlertDialogCancel>取消</AlertDialogCancel>
          <AlertDialogAction
            @click="confirmDelete"
            class="bg-red-500 hover:bg-red-600"
          >
            删除
          </AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>

    <!-- 图片预览遮罩 -->
    <ImagePreviewModal
      :visible="previewModalVisible"
      :src="currentPreviewImage?.url || ''"
      :title="currentPreviewImage?.name || ''"
      :upload-time="currentPreviewImage?.uploadTime"
      @close="closePreviewModal"
    />
  </main>
</template>

<script setup lang="ts">
import { ref, computed, watch, nextTick, onMounted } from "vue";
import { useRouter } from "vue-router";
import { useMaterialStore } from "../stores/material";
import { Button } from "../components/ui/button";
import { Input } from "../components/ui/input";
import { ScrollArea } from "../components/ui/scroll-area";
import {
  Select,
  SelectTrigger,
  SelectContent,
  SelectItem,
} from "../components/ui/select";
import AlertDialog from "../components/ui/alert-dialog/AlertDialog.vue";
import AlertDialogAction from "../components/ui/alert-dialog/AlertDialogAction.vue";
import AlertDialogCancel from "../components/ui/alert-dialog/AlertDialogCancel.vue";
import AlertDialogContent from "../components/ui/alert-dialog/AlertDialogContent.vue";
import AlertDialogDescription from "../components/ui/alert-dialog/AlertDialogDescription.vue";
import AlertDialogFooter from "../components/ui/alert-dialog/AlertDialogFooter.vue";
import AlertDialogHeader from "../components/ui/alert-dialog/AlertDialogHeader.vue";
import AlertDialogTitle from "../components/ui/alert-dialog/AlertDialogTitle.vue";
import AlertDialogTrigger from "../components/ui/alert-dialog/AlertDialogTrigger.vue";
import ImagePreview from "../components/ImagePreview.vue";
import ImagePreviewModal from "../components/ImagePreviewModal.vue";
import { advancedSearch } from "../api/search";
import { deleteImage } from "../api/materialImage";
import { getAllTags } from "../api/tag";
import { Badge } from "../components/ui/badge";

const router = useRouter();
const materialStore = useMaterialStore();
const images = computed(() => materialStore.images);

// 标签相关状态
const allTags = ref<string[]>([]);
const isLoadingTags = ref(false);
const tagsError = ref<string | null>(null);

// 获取所有标签
async function fetchAllTags() {
  isLoadingTags.value = true;
  tagsError.value = null;

  try {
    const res = await getAllTags();

    // 兼容不同的接口返回格式
    let tags: string[] = [];
    if (res && Array.isArray(res.data)) {
      // 如果返回的是标签对象数组，提取 name 字段
      tags = res.data
        .map((tag: any) =>
          typeof tag === "string" ? tag : tag.name || tag.tagName || ""
        )
        .filter(Boolean);
    } else if (res && res.data && Array.isArray(res.data.data)) {
      tags = res.data.data
        .map((tag: any) =>
          typeof tag === "string" ? tag : tag.name || tag.tagName || ""
        )
        .filter(Boolean);
    }

    allTags.value = [...new Set(tags)].sort(); // 去重并排序
  } catch (error) {
    console.error("获取标签失败:", error);
    tagsError.value = "获取标签失败，请刷新页面重试";
    allTags.value = [];
  } finally {
    isLoadingTags.value = false;
  }
}

// 分页相关
const pageSize = 20; // 每页显示20张图片
const currentPage = ref(1);
const totalCount = ref(0);
const totalPages = computed(() =>
  Math.max(1, Math.ceil(totalCount.value / pageSize))
);

// 筛选和排序状态
const selectedImageId = ref<string | null>(null);
const search = ref("");
const tagFilter = ref("");
const selectedTags = ref<string[]>([]);
const sortMode = ref<"time" | "count">("time");
const sortDirection = ref<"asc" | "desc">("desc");
const viewMode = ref<"grid" | "list">("grid");
const timeRange = ref<"all" | "today" | "week" | "month" | "quarter" | "year">(
  "all"
);
const usageFilter = ref<"all" | "unused" | "low" | "medium" | "high">("all");
const showFilters = ref(false);

// 删除确认对话框状态
const deleteDialogOpen = ref(false);
const imageToDelete = ref<any>(null);

// 图片预览遮罩状态
const previewModalVisible = ref(false);
const currentPreviewImage = ref<any>(null);

// 选中的图片
const selectedImage = computed(() => {
  if (!selectedImageId.value) return null;
  return images.value.find(img => img.id === selectedImageId.value) || null;
});

// 防抖搜索
let searchTimeout: number;
const isSearching = ref(false); // 搜索状态指示器
const isComposing = ref(false); // 拼音输入状态

const handleSearchInput = () => {
  // 如果正在拼音输入，不触发搜索
  if (isComposing.value) {
    return;
  }

  clearTimeout(searchTimeout);
  searchTimeout = setTimeout(() => {
    currentPage.value = 1; // 重置到第一页
    isSearching.value = true; // 开始搜索
    fetchImages().finally(() => {
      isSearching.value = false; // 搜索完成
    });
  }, 500); // 增加防抖时间到500ms
};

const handleCompositionStart = () => {
  isComposing.value = true; // 开始拼音输入
  isSearching.value = true; // 显示搜索状态
};

const handleCompositionEnd = () => {
  isComposing.value = false; // 结束拼音输入
  isSearching.value = false; // 隐藏搜索状态

  // 拼音输入完成后，立即触发搜索
  clearTimeout(searchTimeout);
  searchTimeout = setTimeout(() => {
    currentPage.value = 1; // 重置到第一页
    isSearching.value = true; // 开始搜索
    fetchImages().finally(() => {
      isSearching.value = false; // 搜索完成
    });
  }, 300); // 拼音输入完成后使用较短的防抖时间
};

const handleSearchEnter = () => {
  clearTimeout(searchTimeout); // 清除之前的防抖
  currentPage.value = 1; // 重置到第一页
  isSearching.value = true; // 开始搜索
  fetchImages().finally(() => {
    isSearching.value = false; // 搜索完成
  });
};

const handleFilterChange = () => {
  currentPage.value = 1;
};

const handleSortChange = () => {
  currentPage.value = 1;
  fetchImages();
};

// 排序方向变化处理
const handleSortDirectionChange = () => {
  currentPage.value = 1;
  fetchImages();
};

// 多标签筛选
const toggleTag = (tag: string) => {
  const index = selectedTags.value.indexOf(tag);
  if (index > -1) {
    selectedTags.value.splice(index, 1);
  } else {
    selectedTags.value.push(tag);
  }
  currentPage.value = 1;

  // 触发高级搜索
  fetchImages();
};

// 时间范围筛选
const handleTimeRangeChange = () => {
  currentPage.value = 1;
  fetchImages();
};

const getTimeRangeLabel = (range: string) => {
  const labels = {
    all: "全部时间",
    today: "今天",
    week: "本周",
    month: "本月",
    quarter: "本季度",
    year: "今年",
  };
  return labels[range as keyof typeof labels] || "全部时间";
};

// 使用次数筛选
const handleUsageFilterChange = () => {
  currentPage.value = 1;
  fetchImages();
};

const getUsageFilterLabel = (filter: string) => {
  const labels = {
    all: "全部",
    unused: "未使用",
    low: "使用较少",
    medium: "使用中等",
    high: "使用频繁",
  };
  return labels[filter as keyof typeof labels] || "全部";
};

// 清除所有筛选
const clearAllFilters = () => {
  search.value = "";
  tagFilter.value = "";
  selectedTags.value = [];
  timeRange.value = "all";
  usageFilter.value = "all";
  sortMode.value = "time";
  sortDirection.value = "desc";
  currentPage.value = 1;
  fetchImages();
};

// 切换筛选区域显示/隐藏
const toggleFilters = () => {
  showFilters.value = !showFilters.value;
};

// 选择图片（单选）
const selectImage = (imageId: string) => {
  selectedImageId.value = selectedImageId.value === imageId ? null : imageId;

  // 如果选中了图片，立即存储到 store 中
  if (selectedImageId.value) {
    const selectedImg = images.value.find(
      img => img.id === selectedImageId.value
    );
    if (selectedImg) {
      materialStore.setSelectedImageForAction(selectedImg);
    }
  } else {
    // 如果取消选择，清除 store 中的选中图片
    materialStore.clearSelectedImageForAction();
  }
};

// 清除选择
const clearSelection = () => {
  selectedImageId.value = null;
};

// 打开删除确认对话框
const openDeleteDialog = (img: any) => {
  imageToDelete.value = img;
  deleteDialogOpen.value = true;
};

// 确认删除图片
const confirmDelete = async () => {
  if (imageToDelete.value) {
    try {
      // 先调用后台删除接口
      await deleteImage(Number(imageToDelete.value.id));

      // 后台删除成功后，重新获取当前页数据
      await fetchImages();

      // 如果删除的是当前选中的图片，清除选中状态
      if (selectedImageId.value === imageToDelete.value.id) {
        selectedImageId.value = null;
        // 同时清除 store 中的选中图片
        materialStore.clearSelectedImageForAction();
      }

      // 关闭对话框并清除待删除图片
      deleteDialogOpen.value = false;
      imageToDelete.value = null;
    } catch (error) {
      console.error("删除图片失败:", error);
      // 可以在这里添加错误提示
    }
  }
};

// 跳转到文案生成页面
const goToTextGeneration = () => {
  if (selectedImage.value) {
    // 图片已经自动存储到 store 中，直接跳转
    router.push("/copywriting");
  }
};

// 跳转到图片扩展页面
const goToImageExpansion = () => {
  if (selectedImage.value) {
    // 图片已经自动存储到 store 中，直接跳转
    router.push("/expand");
  }
};

// 优化后的筛选逻辑
const filteredImages = computed(() => {
  let arr = images.value;

  // 搜索过滤
  if (search.value.trim()) {
    const kw = search.value.trim().toLowerCase();
    arr = arr.filter(
      img =>
        img.name.toLowerCase().includes(kw) ||
        img.tags.some(t => t.toLowerCase().includes(kw))
    );
  }

  // 单标签过滤
  if (tagFilter.value) {
    arr = arr.filter(img => img.tags.includes(tagFilter.value));
  }

  // 多标签过滤
  if (selectedTags.value.length > 0) {
    arr = arr.filter(img =>
      selectedTags.value.some(tag => img.tags.includes(tag))
    );
  }

  // 时间范围过滤
  if (timeRange.value !== "all") {
    const now = Date.now();
    const ranges = {
      today: 24 * 60 * 60 * 1000,
      week: 7 * 24 * 60 * 60 * 1000,
      month: 30 * 24 * 60 * 60 * 1000,
      quarter: 90 * 24 * 60 * 60 * 1000,
      year: 365 * 24 * 60 * 60 * 1000,
    };
    const rangeMs = ranges[timeRange.value as keyof typeof ranges] || 0;
    arr = arr.filter(img => now - img.uploadTime <= rangeMs);
  }

  // 使用次数过滤
  if (usageFilter.value !== "all") {
    const filters = {
      unused: (count: number) => count === 0,
      low: (count: number) => count >= 1 && count <= 5,
      medium: (count: number) => count >= 6 && count <= 20,
      high: (count: number) => count > 20,
    };
    const filterFn = filters[usageFilter.value as keyof typeof filters];
    if (filterFn) {
      arr = arr.filter(img => filterFn(img.usedCount));
    }
  }

  // 排序
  if (sortMode.value === "time") {
    arr = arr.slice().sort((a, b) => {
      const diff = b.uploadTime - a.uploadTime;
      return sortDirection.value === "desc" ? diff : -diff;
    });
  } else if (sortMode.value === "count") {
    arr = arr.slice().sort((a, b) => {
      const diff = b.usedCount - a.usedCount;
      return sortDirection.value === "desc" ? diff : -diff;
    });
  }

  return arr;
});

// 分页后的图片
const paginatedImages = computed(() => materialStore.images);

// 监听筛选条件变化，重置分页
watch([tagFilter, sortMode, sortDirection], () => {
  currentPage.value = 1;
});

function displayTags(tags: string[]) {
  if (tags.length <= 2) return tags;
  return [tags[0], tags[1], "__more__"];
}

function formatDate(ts: number) {
  const d = new Date(ts);
  return d.toISOString().slice(0, 10);
}

const sortModeLabel = computed(() =>
  sortMode.value === "time" ? "按时间排序" : "按使用频率排序"
);

// 打开图片预览遮罩
const openPreviewModal = (img: any) => {
  currentPreviewImage.value = img;
  previewModalVisible.value = true;
};

// 关闭图片预览遮罩
const closePreviewModal = () => {
  previewModalVisible.value = false;
  currentPreviewImage.value = null;
};

// 处理 ImagePreview 组件的预览事件
const handleImagePreview = (src: string, alt: string) => {
  // 找到对应的图片对象
  const img = images.value.find(img => img.url === src);
  if (img) {
    openPreviewModal(img);
  }
};

// 下载图片
function downloadImage(img: any) {
  // 这里可以实现图片下载功能
  console.log("下载图片:", img.name);
  // 可以创建一个临时的 a 标签来下载图片
  const link = document.createElement("a");
  link.href = img.url;
  link.download = img.name;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}

// 页面加载和分页/排序/筛选变化时获取图片数据
onMounted(() => {
  fetchImages();
  fetchAllTags(); // 同时获取标签数据
});
watch(
  [currentPage, sortMode, sortDirection, selectedTags, timeRange, usageFilter],
  fetchImages
);

async function fetchImages() {
  const userId = "";

  // 构建高级搜索参数
  const searchParams: any = {
    page: currentPage.value - 1, // 接口页码从0开始
    size: pageSize,
    sortBy: sortMode.value === "time" ? "createdAt" : "usageCount",
    sortDir: sortDirection.value,
  };

  // 搜索关键词
  if (search.value.trim()) {
    searchParams.keyword = search.value.trim();
  }

  // 标签筛选
  if (selectedTags.value.length > 0) {
    searchParams.tags = selectedTags.value;
  }

  // 时间范围筛选
  if (timeRange.value !== "all") {
    const now = new Date();
    let startDate: Date;

    switch (timeRange.value) {
      case "today":
        startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate());
        break;
      case "week":
        startDate = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
        break;
      case "month":
        startDate = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
        break;
      case "quarter":
        startDate = new Date(now.getTime() - 90 * 24 * 60 * 60 * 1000);
        break;
      case "year":
        startDate = new Date(now.getTime() - 365 * 24 * 60 * 60 * 1000);
        break;
      default:
        startDate = new Date(0);
    }

    // 格式化为 yyyy-MM-dd HH:mm:ss
    const formatDateTime = (date: Date) => {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      const hours = String(date.getHours()).padStart(2, "0");
      const minutes = String(date.getMinutes()).padStart(2, "0");
      const seconds = String(date.getSeconds()).padStart(2, "0");
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    };

    searchParams.startDate = formatDateTime(startDate);
    searchParams.endDate = formatDateTime(now);
  }

  // 使用次数筛选
  if (usageFilter.value !== "all") {
    const usageRanges = {
      unused: { minUsage: 0, maxUsage: 0 },
      low: { minUsage: 1, maxUsage: 5 },
      medium: { minUsage: 6, maxUsage: 20 },
      high: { minUsage: 21, maxUsage: 999999 },
    };

    const range = usageRanges[usageFilter.value as keyof typeof usageRanges];
    if (range) {
      searchParams.minUsage = range.minUsage;
      searchParams.maxUsage = range.maxUsage;
    }
  }

  try {
    const res = await advancedSearch(searchParams);
    let list = [];
    let total = 0;

    console.log("API响应:", res);

    // 根据实际响应结构处理数据
    if (res && res.data && Array.isArray(res.data)) {
      list = res.data.map((item: any) => ({
        id: String(item.id),
        name: item.name,
        originalName: item.originalName,
        url: item.fileUrl,
        tags: item.tags || [],
        usedCount: item.usageCount ?? 0,
        uploadTime: item.createdAt
          ? new Date(item.createdAt).getTime()
          : Date.now(),
        isFavorite: false, // 默认不收藏，后续会从 localStorage 同步
      }));

      // 处理分页信息
      if (res.pagination) {
        total = res.pagination.totalElements || 0;
        // 注意：接口返回的页码从0开始，前端从1开始
        currentPage.value = (res.pagination.currentPage || 0) + 1;
      } else {
        total = list.length;
      }
    } else if (res && Array.isArray(res.data)) {
      // 兼容其他格式
      list = res.data.map((item: any) => ({
        id: String(item.id),
        name: item.name,
        originalName: item.originalName,
        url: item.fileUrl,
        tags: item.tags || [],
        usedCount: item.usageCount ?? 0,
        uploadTime: item.createdAt
          ? new Date(item.createdAt).getTime()
          : Date.now(),
        isFavorite: false, // 默认不收藏，后续会从 localStorage 同步
      }));
      total = res.totalElements || res.total || list.length;
    }

    materialStore.images = list;
    totalCount.value = total;

    console.log("分页信息:", {
      currentPage: currentPage.value,
      totalPages: totalPages.value,
      totalCount: totalCount.value,
      listLength: list.length,
      shouldShowPagination: totalCount.value > pageSize,
    });
  } catch (e) {
    console.error("获取图片失败:", e);
    materialStore.images = [];
    totalCount.value = 0;
  }
}

const tagColors = [
  { bg: "bg-pink-100", text: "text-pink-700" },
  { bg: "bg-blue-100", text: "text-blue-700" },
  { bg: "bg-green-100", text: "text-green-700" },
  { bg: "bg-yellow-100", text: "text-yellow-700" },
  { bg: "bg-purple-100", text: "text-purple-700" },
  { bg: "bg-orange-100", text: "text-orange-700" },
  { bg: "bg-cyan-100", text: "text-cyan-700" },
  { bg: "bg-rose-100", text: "text-rose-700" },
];
function getTagColor(tag: string, idx: number) {
  // 用tag的hash或idx分配颜色
  let hash = 0;
  for (let i = 0; i < tag.length; i++)
    hash = tag.charCodeAt(i) + ((hash << 5) - hash);
  const colorIdx = Math.abs(hash) % tagColors.length;
  return tagColors[colorIdx];
}

function toggleFavorite(img: any) {
  let ids = JSON.parse(localStorage.getItem("favoriteImageIds") || "[]");
  const idx = ids.indexOf(img.id);
  if (idx > -1) {
    ids.splice(idx, 1); // 取消收藏
    img.isFavorite = false;
  } else {
    ids.push(img.id); // 收藏
    img.isFavorite = true;
  }
  localStorage.setItem("favoriteImageIds", JSON.stringify(ids));
}

// 页面初始化时同步收藏状态
onMounted(() => {
  const ids = JSON.parse(localStorage.getItem("favoriteImageIds") || "[]");
  images.value.forEach(img => {
    img.isFavorite = ids.includes(img.id);
  });
});
</script>

<style>
.material-fade-enter-active,
.material-fade-leave-active {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}
.material-fade-enter-from {
  opacity: 0;
  transform: scale(0.98) translateY(30px);
}
.material-fade-enter-to {
  opacity: 1;
  transform: scale(1) translateY(0);
}
.material-fade-leave-from {
  opacity: 1;
  transform: scale(1) translateY(0);
}
.material-fade-leave-to {
  opacity: 0;
  transform: scale(0.98) translateY(-30px);
}
.detail-fade-enter-active,
.detail-fade-leave-active {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}
.detail-fade-enter-from {
  opacity: 0;
  transform: translateY(30px) scale(0.98);
}
.detail-fade-enter-to {
  opacity: 1;
  transform: translateY(0) scale(1);
}
.detail-fade-leave-from {
  opacity: 1;
  transform: translateY(0) scale(1);
}
.detail-fade-leave-to {
  opacity: 0;
  transform: translateY(-30px) scale(0.98);
}
</style>
